﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class magikSpells : MonoBehaviour
{
    [SerializeField]
    private float offsetX=0;
    [SerializeField]
    private float offsetY=0;
    [SerializeField]
    private GameObject ae;
    private Rigidbody2D spellRB;
    [SerializeField]
    private float spellSpeed;
    private Transform source;
    //private Transform trgt;
    public Transform MyTRGT { get; private set; }
    // Start is called before the first frame update
    private float dmg;
    void Start()
    {
        spellRB = GetComponent<Rigidbody2D>();
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 direction= MyTRGT.position - transform.position;
        spellRB.velocity = direction.normalized*spellSpeed;
        //spell direction
        float angle= Mathf.Atan2(direction.y,direction.x)*Mathf.Rad2Deg;
        transform.rotation=Quaternion.AngleAxis(angle,Vector3.forward);
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "hitbox" && collision.transform==MyTRGT)
        {
            unit u=collision.GetComponentInParent<unit>();
            spellRB.velocity = Vector2.zero;
            u.ReceiveDMG(dmg,source);
            
            Destroy(gameObject);
    
           
            Instantiate(ae, new Vector2(transform.position.x + offsetX, transform.position.y + offsetY),Quaternion.identity);
        }
        else if(collision.tag=="obstacle")
        {

            Destroy(gameObject);
            Instantiate(ae, new Vector2(transform.position.x + offsetX, transform.position.y + offsetY), Quaternion.identity);
        }
        
    }
    public void inicialize(Transform target, float dmg, Transform source)
    {
        this.MyTRGT = target;
        this.dmg = dmg;
        this.source = source;
    }
}
